package com.huangtang.pc.handler;

import cn.hutool.core.util.StrUtil;
import com.huangtang.pc.enums.BaseEnum;
import com.huangtang.pc.exception.BizException;
import com.huangtang.pc.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 统一异常拦截处理器
 * @author sunjf
 * @date 2024/01/05
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        log.error("参数验证异常：",e);
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(","));
        return Result.error(message, BaseEnum.PARAMETER_ERROR.getLabel());
    }

    @ExceptionHandler(BizException.class)
    public Result<Void> handlerBizException(BizException e){
        log.error("业务异常：",e);
        log.error("业务异常：code={},msg={}",e.getCode(),e.getMsg());
        return Result.error(e.getMsg(),e.getCode());
    }

    @ExceptionHandler(Throwable.class)
    public Result<Void> handlerBizException(Throwable e){
        if(e instanceof BizException){
            BizException bizException = (BizException) e;
            log.error("业务异常：",e);
            log.error("业务异常：code={},msg={}",bizException.getCode(),bizException.getMsg());
            return Result.error(bizException.getMsg(),bizException.getCode());
        }else{
            log.error("未知异常：",e);
            return Result.error(e.getMessage(),BaseEnum.BAD_REQUEST.getLabel());
        }

    }

}


